package com.example.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.MyDataSource;
import com.example.controller.utils.Result;
import com.example.pojo.Book;
import com.example.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
//Rest模式
@RestController
@RequestMapping("/books")
public class BookController {
//    使用Spring的EL表达式读取配置类中的属性
    @Value("${country}")
    private String myCountry;
    @Value("${user.name}")
    private String username;

    @Value("${likes[0]}")
    private String likes1;

    @Value("${users2[1].age}")
    private String age;

//    使用自动装配将所有的数据封装到一个对象

    @Autowired
    private Environment environment;
    @Autowired
    private MyDataSource myDataSource;
    @Autowired
    private BookService bookService;
    @GetMapping("/getAll")
    public Result getAll(){
        return new Result(true,bookService.getAll());
    }

    @GetMapping
    public String getById(){
        System.out.println("test");
        System.out.println("test");
        System.out.println("test");
        System.out.println("test");
        System.out.println("springboot is running");
        System.out.println("name:  "+username);
        System.out.println("country:  "+myCountry);
        System.out.println("likes:  "+likes1);
        System.out.println("age:    "+age);
        System.out.println("============");
        System.out.println(environment.getProperty("country"));
        System.out.println(environment.getProperty("users2[1].age"));
        System.out.println("===============");
        System.out.println(myDataSource);
        return "springboot is running";
    }
    @PostMapping
    public Result save(@RequestBody  Book book) throws Exception {
        if (book.getName().equals("name100")){
            throw new Exception();
        }
        return new Result(bookService.save(book));

    }
    @PutMapping
    public Result update(@RequestBody  Book book){
        return new Result(bookService.update(book));
    }
    @DeleteMapping("{id}")
    public Result delete(@PathVariable("id") Integer id ){
        return new Result(bookService.delete(id));
    }
    @GetMapping("{id}")
    public Result getById(@PathVariable("id") Integer id ){
        return new Result(true, bookService.getById(id));
    }




    @GetMapping("/getPage/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable("currentPage") Integer currentPage,@PathVariable("pageSize") Integer pageSize
                            ,Book book){

        IPage<Book> page = bookService.getPage(currentPage, pageSize,book);
        if (currentPage>page.getPages()){
            page=bookService.getPage((int) page.getPages(), pageSize,book);
        }
        return new Result(true,page);
    }
}
